package com.heima.gateway.app.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(1)
public class AuthorizationFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断访问的是否是登录界面,如果是登录界面直接放行
        String uri = request.getURI().getPath();
        if (uri.contains("/login_auth")){
            //包含,放行
            return chain.filter(exchange);
        }
        //不是,判断是否携带token,与前端约定好将token放在请求头中
        String token = request.getHeaders().getFirst("token");
        //如果是空,表示未登录,给前端直接响应未登录状态码
        if (StringUtils.isEmpty(token)){
            //响应未登录状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }
        //如果不为空,代表携带了token,判断token是否合法
        try {
            //解析
            Claims claims = AppJwtUtil.getClaimsBody(token);
            Integer id = claims.get("id", Integer.class);
            request.mutate().header("userid",String.valueOf(id));
            //不报错,放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //抛异常,给前端响应未登录状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
